package com.xs.smc.config;

import com.xs.smc.entity.Order;
import com.xs.smc.enums.OrderEvent;
import com.xs.smc.enums.OrderStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.action.Action;
import org.springframework.statemachine.config.EnableStateMachine;
import org.springframework.statemachine.config.EnumStateMachineConfigurerAdapter;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;

import java.util.EnumSet;

/**
 * 公众号：程序员徐庶
 */
@Configuration
@EnableStateMachine
public class OrderStateMachineConfig extends EnumStateMachineConfigurerAdapter<OrderStatus, OrderEvent> {

    @Override
    public void configure(StateMachineStateConfigurer<OrderStatus, OrderEvent> states) throws Exception {
        states
            .withStates()
            .initial(OrderStatus.PENDING_CONFIRM)
            .states(EnumSet.allOf(OrderStatus.class));
    }

    @Override
    public void configure(StateMachineTransitionConfigurer<OrderStatus, OrderEvent> transitions) throws Exception {
        transitions
            .withExternal().source(OrderStatus.PENDING_CONFIRM).target(OrderStatus.CONFIRMED).event(OrderEvent.CONFIRM).action(confirmAction())
            .and()
            .withExternal().source(OrderStatus.CONFIRMED).target(OrderStatus.PREPARING).event(OrderEvent.PREPARE).action(prepareAction())
            .and()
            .withExternal().source(OrderStatus.PREPARING).target(OrderStatus.DELIVERING).event(OrderEvent.DELIVER)
            .and()
            .withExternal().source(OrderStatus.DELIVERING).target(OrderStatus.COMPLETED).event(OrderEvent.COMPLETE)
            .and()
            // 已接单和待接单 允许取消
            .withExternal().source(OrderStatus.PENDING_CONFIRM).target(OrderStatus.CANCELLED).event(OrderEvent.CANCEL)
            .and()
            .withExternal().source(OrderStatus.CONFIRMED).target(OrderStatus.CANCELLED).event(OrderEvent.CANCEL);
    }


    // 定义餐厅接单处理 Action
    @Bean
    public Action<OrderStatus, OrderEvent> confirmAction() {
        return context -> {
            // 获取传递的订单信息参数
            Order order = (Order) context.getMessageHeaders().get("order");

            // 餐厅确认业务代码
            System.out.println("餐厅已接单: " + order.getId());
            // 例如推送消息给商家系统
            // 例如更新数据库
            // 其他接单业务...
        };
    }

    // 定义制作开始处理 Action
    @Bean
    public Action<OrderStatus, OrderEvent> prepareAction() {
        return context -> {
            Order order = (Order) context.getMessageHeaders().get("order");

            // 开始制作业务代码
            System.out.println("开始制作订单: " + order.getId());
            // 例如通知厨房系统
            // 更新预计送达时间
            // 其他制作相关业务...
        };
    }
}